package kidsProjectClient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.AbstractMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

import udpSve.UDPNode;

public class Client {

	public static final int PORT = 8988;

	public static void main(String[] args) throws IOException,
			InterruptedException {
		InetAddress addr = InetAddress.getLocalHost();
		//InetAddress addr = InetAddress.getByName("25.127.20.245");
		System.out.println(addr);
		Socket sock = new Socket(addr, PORT);
		System.out.println("g");
		sock.setReuseAddress(true);
		int localPort = sock.getLocalPort();
		BufferedReader inServer = new BufferedReader(new InputStreamReader(
				sock.getInputStream()));
		PrintWriter outServer = new PrintWriter(new BufferedWriter(
				new OutputStreamWriter(sock.getOutputStream())), true);

		System.out.println("Connected to server!");
		int attempts = 0;
		while (!inServer.ready() && attempts < 500) {
			attempts++;
			Thread.sleep(10);
		}
		String opseg = inServer.readLine();
		System.out.println("primio opseg: "+ opseg);

		List<Entry<InetAddress, Integer>> lastClients = new LinkedList<Entry<InetAddress, Integer>>();
		while (true) {
			String line = inServer.readLine();
			if (line.equals("#FINISHED_SENDING_LAST_CLIENTS$"))
				break;

			String line2 = inServer.readLine();

			InetAddress address = InetAddress.getByName(line);
			Integer port = Integer.parseInt(line2);
			Entry<InetAddress, Integer> clientEntry = new AbstractMap.SimpleEntry<InetAddress, Integer>(
					address, port);
			lastClients.add(clientEntry);
		}
		
		sock.close();
		System.out.println("MOJ PORT: " + localPort);
		UDPNode udpn = new UDPNode(opseg, localPort, lastClients);
		udpn.start();
	}
}
